package com.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class StaticContentCacheTimeControl implements Filter {

	private int htmlTime;
	private int cssTime;
	private int jsTime;

	public void init(FilterConfig filterConfig) throws ServletException {
		String html = filterConfig.getInitParameter("html");
		htmlTime = Integer.parseInt(html);
		String css = filterConfig.getInitParameter("css");
		cssTime = Integer.parseInt(css);
		String js = filterConfig.getInitParameter("js");
		jsTime = Integer.parseInt(js);
	}

	public void destroy() {

	}

	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		// 1.转换请求和响应
		HttpServletRequest request;
		HttpServletResponse response;
		try {
			request = (HttpServletRequest) req;
			response = (HttpServletResponse) res;
		} catch (ClassCastException e) {
			throw new ServletException("non-HTTP request or response");
		}
		
		//2.拿到请求的uri
		String uri = request.getRequestURI() ;
		//3.拿到请求的后缀名
		if(uri.indexOf(".")!= -1){
			int index = uri.indexOf(".") ;
			String extendsName = uri.substring(index + 1) ;
			//4.判断后缀名
			long time = System.currentTimeMillis() ;
			
			if("html".equals(extendsName))
				time += htmlTime * 3600 * 1000 ;
			
			else if("css".equals(extendsName))
				time += cssTime * 3600 * 1000 ;
			else
				time += jsTime * 3600 * 1000 ;
			
			response.setDateHeader("expires", time) ;
		}
		
		//放行
		chain.doFilter(request, response) ;
	}
}
